package fxs.com.enter_work_space;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

public class FileActivity extends AppCompatActivity {
    Stack<File> fileStack = new Stack<>();
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE"};
    ListView listView;
    FileAdapter ad ;
    File currentFile = null;
    File ret;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_file);
        int permission = ActivityCompat.checkSelfPermission(this,
                "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限，去申请写的权限，会弹出对话框
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        } else {
            queryFiles();
        }
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currentFile = fileStack.pop();
                if(currentFile!=null){
                    ad.setDatas(Arrays.asList(currentFile.listFiles()));
                    ad.notifyDataSetChanged();
                }else{
                    FileActivity.this.finish();
                }
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults != null && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
            queryFiles();
        } else {
            Toast.makeText(this, "权限申请失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void queryFiles() {
        File externalStorageDirectory = Environment.getExternalStorageDirectory();
        currentFile = externalStorageDirectory;
        listView = findViewById(R.id.list_item);
        ad = new FileAdapter(Arrays.asList(externalStorageDirectory.listFiles()),this);
        listView.setAdapter(ad);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                fileStack.push(currentFile);
                File file = (File) ad.getItem(position);
                currentFile = file;
                if(file.isDirectory()){
                    ad.setDatas(Arrays.asList(file.listFiles()));
                    ad.notifyDataSetChanged();

                }else{
                  if(isImageFile(file.getPath())){
                      ret = file;
                      Intent intent = new Intent();
                      intent.putExtra("file",file.getPath());
                      setResult(1000,intent);
                      FileActivity.this.finish();
                  }else{
                      Toast.makeText(view.getContext(),"请选择你的二维码",Toast.LENGTH_SHORT).show();
                  }
                }
            }
        });


    }

    public static boolean isImageFile(String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        if (options.outWidth == -1) {
            return false;
        }
        return true;
    }


    class FileAdapter extends BaseAdapter {

        List<File> datas;
        Context context;

        public FileAdapter(List<File> datas, Context context) {
            this.datas = datas;
            this.context = context;
        }

        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public Object getItem(int position) {
            return datas.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        public List<File> getDatas() {
            return datas;
        }

        public void setDatas(List<File> datas) {
            this.datas = datas;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            View view = null;
            if (convertView == null) {
                holder = new ViewHolder();
                view = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
                holder.item = view.findViewById(R.id.text_item);
                view.setTag(holder);
            } else {
                view = convertView;
                holder = (ViewHolder) view.getTag();
            }
            holder.item.setText(datas.get(position).getName());
            return view;
        }

        class ViewHolder {
            TextView item;
        }
    }


}
